package server;

import server.container.Context;
import server.container.Host;
import server.container.Mapper;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Map<String,HttpServlet> servletMap;


    public RequestProcessor(Socket socket) {
        this.socket = socket;

    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            Mapper mapper = Mapper.getInstance();
            Host host = mapper.getHostByHostPath(request.getHost());

            Context context = host.getContextByPath(request.getContextPath());

            if(context == null) {
                response.outputHtml(request.getUrl());
            }else{
                this.servletMap = context.getServletMap();

                String serveletPath = request.getUrl().substring(request.getContextPath().length());
                // 静态资源处理
                if(servletMap.get(serveletPath) == null) {
                    response.outputHtml(request.getUrl());
                }else{
                    // 动态资源servlet请求
                    HttpServlet httpServlet = servletMap.get(serveletPath);
                    httpServlet.service(request,response);
                }

            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
